<template>
  <div id="roles">
      <el-breadcrumb separator-class="el-icon-arrow-right">
        <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item>权限管理</el-breadcrumb-item>
        <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>

    <el-card>
        <el-row><el-col><el-button type="primary" @click="showRoleDialog()">添加角色</el-button></el-col></el-row>
        <el-table  :data="rolelist" border>
            <el-table-column type="expand" width="50">
                <template slot-scope="scope">
                    <el-row :class="['rowbottomborder',itemindex==0 ? 'rowtopborder':'','vcenter']" v-for="(item,itemindex) in scope.row.children" :key="item.id">
                        <!-- 一级权限 -->
                        <el-col :span="5">
                            <el-tag @close="deleteRoleRightById(scope.row,item.id)" closable>{{item.authName}}</el-tag>
                            <i class="el-icon-caret-right"></i>
                        </el-col>
                        <!-- 二级权限 -->
                        <el-col :span="19">
                            <el-row :class="[sitemindex==0 ? '':'rowtopborder','vcenter']" v-for="(sitem,sitemindex) in item.children" :key="sitem.id">
                                <el-col :span="6">
                                    <el-tag @close="deleteRoleRightById(scope.row,sitem.id)" closable type="success">{{sitem.authName}}</el-tag>
                                    <i class="el-icon-caret-right"></i>
                                </el-col>
                                <!-- 三级权限 -->
                                <el-col :span="18">
                                    <el-tag @close="deleteRoleRightById(scope.row,ssitem.id)" closable type="warning" v-for="ssitem in sitem.children" :key="ssitem.id">{{ssitem.authName}}</el-tag>
                                </el-col>
                            </el-row>
                        </el-col>   
                    </el-row>
                </template>
            </el-table-column>
            <el-table-column type="index" label="序号" width="50"> </el-table-column>
            <el-table-column prop="roleName" label="角色名称" > </el-table-column>
            <el-table-column prop="roleDesc" label="角色描述" > </el-table-column>
            <el-table-column  label="操作" >
                <template slot-scope="scope">
                    <el-button type="primary" @click="showRoleDialog(scope.row)"  size="small" icon="el-icon-edit">编辑</el-button>
                    <el-button type="danger"   size="small" icon="el-icon-delete" @click="deleteRoleById(scope.row.id)">删除</el-button>
                    <el-button type="warning"  size="small" icon="el-icon-setting" @click="setRightDialog(scope.row)">分配权限</el-button>   
                </template>
            </el-table-column>
        </el-table>
    </el-card>

<!-- 角色对话框 -->
    <el-dialog
        :title="roleDialog.title"
        :visible.sync="roleDialog.visible"
        @close="setRoleDialogClosed()"
        width="50%">
        <!-- 表单区域 -->
        <el-form :model="roleInfo" :rules="roleFormRules" ref="roleFormRef" label-width="100px" class="demo-ruleForm">
            <el-form-item label="角色名称" prop="roleName">
                <el-input v-model="roleInfo.roleName"></el-input>
            </el-form-item>

            <el-form-item label="角色描述">
                <el-input v-model="roleInfo.roleDesc"></el-input>
            </el-form-item>
        </el-form>

        <span slot="footer" class="dialog-footer">
            <el-button @click="roleDialog.visible = false">取 消</el-button>
            <el-button type="primary" @click="saveRole">确 定</el-button>
        </span>
    </el-dialog>


    <!-- 分配权限对话框 -->
    <el-dialog
        title="分配权限"
        :visible.sync="setRightDialogVisible"
        @close="setRightDialogClosed()"
        width="50%">
        <!-- tree控件 -->
        <el-tree :data="rightlist" :props="treeProps" show-checkbox node-key="id" default-expand-all :default-checked-keys="defKeys" ref="treeRef">
        </el-tree>

        <span slot="footer" class="dialog-footer">
            <el-button @click="setRightDialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="saveRight">确 定</el-button>
        </span>
    </el-dialog>

  </div>
</template>

<script>

export default {
  name: 'roles',
  data() {
      return {
          rolelist:[],
          rightlist:[],
          setRightDialogVisible:false,
          treeProps:{
              label:'authName',
              children:'children'
          },
          defKeys:[],
          roleId:'',
          roleDialog:{
              title:'',
              visible:false
          },
          roleInfo:{
              id:0,
              roleName:'',
              roleDesc:'',
              children:[]
          },
          oprator:'',
          roleFormRules:{
              roleName:[{ required: true, message: '请输入角色名', trigger: 'blur' }]
          }
      }
  },
  created(){
      this.getRoles()
  },
  methods:{
      async getRoles(){
          const{data:res}=await this.$http.get('roles')
          if(res.meta.status!=200){
              this.$message.error('请求数据失败')
          }
          this.rolelist=res.data
      },
      showRoleDialog(row){
          if(!row){
              this.roleDialog.title='添加角色信息'
              this.oprator="add"
          }else{
              this.roleDialog.title='编辑角色信息'
              this.roleInfo=row
          }
          this.roleDialog.visible=true
      },
      setRoleDialogClosed(){
          this.roleDialog.title=''
          this.oprator=''
          this.roleDialog.visible=false
          this.roleInfo={}
          this.$refs.roleFormRef.resetFields()
      },
       saveRole(){
          if(this.oprator=='add'){
              this.$refs.roleFormRef.validate(async valid=>{
                if(!valid)return
                const{data:res}=await this.$http.post('roles',{roleName:this.roleInfo.roleName,roleDesc:this.roleInfo.roleDesc})
                if(res.meta.status!=201){
                    return this.$message.error(res.meta.msg)
                }
                this.getRoles()
                this.$message.success(res.meta.msg)
                this.roleDialog.visible=false
              })
              

              
          }else{
              this.$refs.roleFormRef.validate(async valid=>{
                if(!valid)return
                    const{data:res}=await this.$http.put(`roles/${this.roleInfo.id}`,{roleName:this.roleInfo.roleName,roleDesc:this.roleInfo.roleDesc})
                if(res.meta.status!=200){
                    return this.$message.error(res.meta.msg)
                }
                this.getRoles()
                this.$message.success(res.meta.msg)
                this.roleDialog.visible=false
              })
          }
      },
      async deleteRoleRightById(role,rightid){
          const result=await this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).catch(err=>err)

        if(result!='confirm'){
            return this.$message.info('取消删除')
        }

        const{data:res}=await this.$http.delete(`roles/${role.id}/rights/${rightid}`)
        if(res.meta.status!=200){
            return this.$message.error('删除失败')
        }
        
        role.children=res.data
      },
      async deleteRoleById(id){
        const result=await this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).catch(err=>err)

        if(result!='confirm'){
            return this.$message.info('取消删除')
        }
        const{data:res}=await this.$http.delete(`roles/${id}`)
        if(res.meta.status!=200){
            return this.$message.error(res.meta.msg)
        }
        this.$message.success(res.meta.msg)
        this.getRoles()
      },
      async setRightDialog(role){
          const{data:res}=await this.$http.get('rights/tree')
          if(res.meta.status!=200){
              return this.$message.error('获取权限失败')
          }
          this.rightlist=res.data
          this.getLeafKeys(role,this.defKeys)
          this.roleId=role.id
          this.setRightDialogVisible=true
      },
      setRightDialogClosed(){
          this.defKeys=[]
      },
    //   通过递归的形式，获取当前角色下的所有3级权限id并保存
      getLeafKeys(node,arr){
          if(!node.children){
              return arr.push(node.id)
          }
          node.children.forEach(item=>{
              this.getLeafKeys(item,arr)
          })
      },
      async saveRight(){
        //   获取半选和全选的id
          const keys=[
         ... this.$refs.treeRef.getCheckedKeys(),
          ...this.$refs.treeRef.getHalfCheckedKeys()]
          const ids=keys.join(',')

          const{data:res}=await this.$http.post(`roles/${this.roleId}/rights`,{rids:ids})
          if(res.meta.status!=200){
              return this.$message.error('授权失败')
          }
          this.setRightDialogVisible=false
          this.getRoles()
          this.$message.success('授权成功')

      }

  }
}
</script>

<style>
    .el-tag{
        margin: 10px;
    }
    .rowtopborder{
        border-top: 1px solid #eee;
    }
    .rowbottomborder{
        border-bottom: 1px solid #eee;
    }
    .vcenter{
        display: flex;
        align-items: center;
    }
</style>
